#include <stdio.h>
#include "funconfig.h"
#include "util.h"
#include "register.h"
#include "instruct.h"





natives funList[]={initfunc(print),initfunc(sleep),initfunc(gpio)};
instruct inst[]={instructInit(jmp),
				instructInit(mov),
				instructInit(push),
				instructInit(pop),
				instructInit(add),
				instructInit(sub),
				instructInit(mul),
				instructInit(call),
				instructInit(cmp),
				instructInit(div),
				instructInit(load),
				instructInit(store),
				instructInit(ret)
				};
//通过下标索引
instructP insTemp[255];
char code[1024*2]={0};
int console=0;
int main(int argc,char**argv){
	int size=loadCode(argv[1],code);
	int *p=(int*)code;
	Register R;
	R.code=code;
	R.RPC=*p;
	R.funList=&funList;
	R.funSize=sizeof(funList)/sizeof(natives);
	char opt=0;
	char isRun=0;
	int optSize=sizeof(inst)/sizeof(instruct);
	
	for(int i=0;i<255;i++){
		insTemp[i]=0;
		for(int j=0;j<optSize;j++){
			if(inst[j].isRun(i)>0){
				insTemp[i]=&inst[j];
				break;
			}
		}
	}


	printf("----------start------------\r\n");
	while(1){
		opt=code[R.RPC];
		if(console==1){
			printf("AX:%04X BX:%04X CX:%04X DX:%04X\r\n"
				"EX:%04X BP:%04X SS:%04X SP:%04X\r\n"
				"PC:%08X\r\n",R.RAX,R.RBX,R.RCX,R.RDX,R.REX,R.RBP,
				 R.RSS,R.RSP,R.RPC);
			printf("opt:%02XH\r\n",opt);
		}
		//printf("opt:%02X %04X %04X \r\n",opt,R.RSP,R.RSS);
		//这个地方效率太低了，可以通过数组直接下表索引来处理
		isRun=0;
		if(insTemp[opt]!=NULL){
			insTemp[opt]->parseRun(&R);
			isRun=1;
		}
		if(isRun==0){
			break;
		}
	}
	printf("progrom exit...\r\n");
	return 0;
}